package base

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"

	"github.com/atotto/clipboard"
	"github.com/flopp/go-findfont"
)

func Inits() {
	//设置中文字体:解决中文乱码问题
	fontPaths := findfont.List()
	for _, path := range fontPaths {
		if strings.Contains(path, "msyh.ttf") || strings.Contains(path, "simhei.ttf") || strings.Contains(path, "simsun.ttc") || strings.Contains(path, "simkai.ttf") {
			os.Setenv("FYNE_FONT", path)
			break
		}
	}
}

// get请求
func Get(apiUrl string) string {
	//URL param
	data := url.Values{}
	data.Set("name", "xiaomi")
	data.Set("age", "18")
	//把string转换为url
	u, err := url.ParseRequestURI(apiUrl)
	if err != nil {
		fmt.Println("parese url requestUrl failed,err：", err)
	}
	//URL encode
	u.RawQuery = data.Encode()
	resp, err := http.Get(u.String())
	if err != nil {
		fmt.Println("get failed, err:", err)
		return ""
	}
	defer resp.Body.Close()
	//读取内容
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed, err:", err)
		return ""
	}

	return string(b)
}

// Post请求
func Post(url string, param map[string]interface{}) string {

	// 表单数据
	//contentType := "application/x-www-form-urlencoded"
	//data := "name=枯藤&age=18"

	// 序列化
	data, err := json.Marshal(param)
	if err != nil {
		fmt.Println("转换失败", err)
		return ""
	}
	// json
	contentType := "application/json"
	// resp, err := http.Post(url, contentType, strings.NewReader(string(data)))
	resp, err := http.Post(url, contentType, bytes.NewBuffer(data))

	/* data := param.Encode()
	contentType := "application/x-www-form-urlencoded"
	resp, err := http.Post(url, contentType, strings.NewReader(data)) */
	if err != nil {
		fmt.Println("post failed, err:", err)
		return ""
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed, err", err)
		return ""
	}
	// fmt.Println(string(b))
	return string(b)
}

// Post请求
func GenerateImgQRCode(url string, param map[string]interface{}) string {

	// 序列化
	data, err := json.Marshal(param)
	if err != nil {
		fmt.Println("转换失败", err)
		return ""
	}
	// json
	contentType := "application/json"
	resp, err := http.Post(url, contentType, strings.NewReader(string(data)))
	if err != nil {
		fmt.Println("post failed, err:", err)
		return ""
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("get resp failed, err", err)
		return ""
	}
	// fmt.Println(string(b))
	return string(b)
}

func Request(urlP string) []byte {
	//请求body
	urlMap := url.Values{}
	urlMap.Add("appid", "tt3a874c3aa5b4178a01")
	urlMap.Add("auditNote", "latest")
	urlMap.Add("auditWay", "")
	urlMap.Add("hostNames", "['douyin']")

	//新建请求
	request, err := http.NewRequest("POST", urlP, strings.NewReader(urlMap.Encode()))
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("request.url: ", request.URL)
	fmt.Println("request.method: ", request.Method)

	//请求头部信息
	request.Header.Add("Authorization", "token1...")
	//post formdata表单请求
	request.Header.Add("Content-Type", "application/x-www-form-urlencoded")

	////发送json格式的参数
	//data := map[string]interface{}{
	//    "user":     "test",
	//    "password": 123,
	//}
	//// 序列化
	//bytesData, _ := json.Marshal(data)
	//request, _ := http.NewRequest("POST", urlP, strings.NewReader(string(bytesData)))
	//请求头设置
	//request.Header.Add("Authorization", "token1...")       //token
	//request.Header.Add("Content-Type", "application/json") //json请求

	//实例化一个客户端
	client := &http.Client{}
	//发送请求到服务端
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err)
		return nil
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	return body
}

// 解析 map[string]interface{} 数据格式
func ParseMap(m map[string]interface{}) {

	fmt.Println("enter print_map########### ")
	for k, v := range m {
		switch value := v.(type) {
		case nil:
			fmt.Println(k, "is nil", "null")
		case string:
			fmt.Println(k, "is string", value)
		case int:
			fmt.Println(k, "is int", value)
		case float64:
			fmt.Println(k, "is float64", value)
		case []interface{}:
			fmt.Println(k, "is an array:")
			for i, u := range value {
				fmt.Println(i, u)
			}
		case map[string]interface{}:
			fmt.Println(k, "is an map:")
			ParseMap(value)
		default:
			fmt.Println(k, "is unknown type", fmt.Sprintf("%T", v))
		}
	}
	fmt.Println("out print_map ########### ")
}

// 复制
func CopyText(value string) {
	// 复制内容到剪切板
	clipboard.WriteAll(value)

	/* // 读取剪切板中的内容到字符串
	content, err := clipboard.ReadAll()
	if err != nil {
		panic(err)
	} */
}

// blob数据转成图片
func BlobDataToImg() {

}

// 字符串截取
func Substr(str string, start int, end int) string {
	tempStr := []rune(str)
	// return string(tempStr[start:end])

	rawStr := string(tempStr[start:end])
	return strings.ReplaceAll(rawStr, "", "")
}
